/**
 * @author ghp
 * @title 在排序数组中查找元素的第一个和最后一个位置
 */
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        int first = findFirst(nums, 0, nums.length - 1, target);
        if (first == -1) {
            return new int[]{-1, -1};
        }
        int last = findLast(nums, 0, nums.length - 1, target);
        return new int[]{first, last};
    }

    private int findLast(int[] nums, int l, int r, int target) {
        while (l < r) {
            int mid = (r - l + 1) / 2 + l; // 向上取整，往右逼近
            if (target >= nums[mid]) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        if (nums[l] != target) {
            return -1;
        }
        return l;
    }

    private int findFirst(int[] nums, int l, int r, int target) {
        while (l < r) {
            int mid = (r - l) / 2 + l; // 向下取整，往左逼近
            if (target <= nums[mid]) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        if (nums[l] != target) {
            return -1;
        }
        return l;
    }
}